package com.hgyc.mom.system.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hgyc.mom.common.enums.CommonStatus;
import com.hgyc.mom.common.exception.AuthException;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.util.RsaUtil;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.system.entity.SysRole;
import com.hgyc.mom.system.entity.SysUser;
import com.hgyc.mom.system.service.SysMenuService;
import com.hgyc.mom.system.service.SysRoleService;
import com.hgyc.mom.system.service.SysUserService;
import com.hgyc.mom.system.vo.LoginVO;
import com.hgyc.mom.system.vo.MenuVO;
import com.hgyc.mom.system.vo.SysUserParam;
import com.hgyc.mom.system.vo.UserInfoVO;
import com.hgyc.mom.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author fwj
 * @since 2025-01-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public void login(LoginVO loginVO) {
        SysUser sysUser = this.getByAccount(loginVO.getUsername());
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        } else {
            if (!sysUser.getStatus().equals(CommonStatus.ENABLE.getValue())) {
                throw new RuntimeException("帐号已停用");
            }
        }

        try {
            String submitPassword = RsaUtil.decrypt(loginVO.getPassword());
            String userPassword = RsaUtil.decrypt(sysUser.getPassword());

            // 解密密码对比是否正确
            if (!userPassword.equals(submitPassword)) {
                throw new AuthException("密码错误");
            }
        } catch (Exception e) {
            throw new AuthException("登录失败！"+e.getMessage());
        }
        StpUtil.login(sysUser.getId());
    }

    @Override
    public SysUser getByAccount(String account) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getAccount, account);
        return getOne(wrapper, false);
    }

    @Override
    public UserInfoVO getUserInfo() {
        UserInfoVO userInfoVO = new UserInfoVO();

        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        SysUser loginUser = getById(userId);
        BeanUtils.copyProperties(loginUser, userInfoVO);

        //获取角色权限
        List<SysRole> userRoles = sysRoleService.getUserRoles(userId);
        userInfoVO.setRoles(userRoles);

        //获取菜单权限
        List<MenuVO> userMenuList = sysMenuService.getUserMenu(userId);
        userInfoVO.setMenus(userMenuList);

        //获取按钮权限
        List<String> userPermission = sysMenuService.getUserPermissions(userId);
        userInfoVO.setPermissions(userPermission);

        //用户token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        userInfoVO.setTokenName(tokenInfo.getTokenName());
        userInfoVO.setTokenValue(tokenInfo.getTokenValue());

        return userInfoVO;
    }

    @Override
    public void editPwd(SysUser sysUser) {
        try {
            String newPassword = RsaUtil.encrypt(sysUser.getPassword());

            LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(SysUser::getId, sysUser.getId());
            wrapper.set(SysUser::getPassword, newPassword);
            this.update(wrapper);
        } catch (Exception e) {
            throw new RuntimeException("修改密码出错");
        }
    }

    @Override
    public void updateUserinfo(SysUser sysUser) {
        SysUser updateUser = getById(sysUser.getId());
        updateUser.setUserPic(sysUser.getUserPic());
        updateUser.setOrgId(sysUser.getOrgId());
        updateUser.setName(sysUser.getName());
        updateUser.setPhone(sysUser.getPhone());
        updateUser.setEmail(sysUser.getEmail());
        updateUser.setStatus(sysUser.getStatus());
        updateById(updateUser);
    }

    @Override
    public void create(SysUser sysUser) {
        //先查询账号是否存在
        String account = sysUser.getAccount();
        if (StringUtils.isEmpty(account)) {
            throw new BizException("账号不能为空！");
        }
        SysUser existUser = this.getByAccount(account);
        if (existUser != null) {
            throw new BizException("该账号已存在，请修改账号！");
        }

        try {
            //新增默认密码 888888
            String password = RsaUtil.encrypt("888888");
            sysUser.setPassword(password);
            this.save(sysUser);
        } catch (Exception e) {
            log.error("新增用户失败：",e);
            throw new BizException("保存失败");
        }
    }

    @Override
    public void batchDel(List<Long> ids) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(SysUser::getId, ids);
        wrapper.set(SysUser::getStatus, CommonStatus.DISABLE.getValue());
        this.update(wrapper);
    }

    @Override
    public IPage<SysUser> rolePage(Page<SysUser> page, SysUserParam sysUserParam) {
        return sysUserMapper.rolePage(page, sysUserParam);
    }
}
